﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using RBAC.Web.Mapper;
using RBAC.Web.Models;
using RBAC.Web.Service;
using RBAC.Web.Utilities;

namespace RBAC.Web.Controllers
{
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListUser(int? page, string sort = "", string sortdir = "asc"
							, String UsernameSearch = ""
				        )    
		{
			//ถ้าตัวมันเป็นลูกของตัวอื่น ต้องทำการ clear ค่า TempData ของแม่ก่อน
				
			// end clear ค่า TempData

			ListUserModel model = new ListUserModel();
            /*GetAllResponseModel<UserModel> temp = Search(new GetAllUserRequestModel()
            {
									 Username = UsernameSearch,
						                    Sort = sort,
					SortType = sortdir == "asc" ? sType.ASC : sType.DESC
            });
            model.ListItems = temp.List;*/
            
            return View(model);
        }

        [HttpPost]
        public ActionResult ListUser(string submitButton, string[] checkbox, ListUserModel input)
        {
            if (ModelState.IsValid)
            {
               switch(submitButton) {
                   case "Search" :
                        input.ListItems = PrepareSearch(input);                      
                        break;
                   default :
                        break;
               }
            }
            return View(input);
        }

		public ActionResult EditUser(String Username)
        {
            ServiceClient service = new ServiceClient();

            GetAllUserRequestDto objGet = new GetAllUserRequestDto()
            {
                EqPk = true,
				Username = StringParser.GetValue<String>(Username)
            };

            var list = service.GetAllUser(objGet);
			UserModel resultModel = null;


			if (list.Data != null && list.Data.Count > 0)
			{
				UserDto resultDto = list.Data[0];
				resultModel = UserMapper.DtoToModel(resultDto);

				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
							}

						SetupRegisterViewModel(resultModel);
            return View(resultModel);
		}

		[HttpPost]
				public ActionResult Update(UserModel inputModel)
				{
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.UpdateUser(UserMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListUserModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));
		
				 // เพิ่ม message แสดงในหน้าแม่
                TempData["UserMessage"] = listDisplay.Message;
                TempData["UserStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["UserId"] = output.Data.Id;
                }
		                return View("ListUser", listDisplay);
		            }   
            else
            {
				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
				                SetupRegisterViewModel(inputModel);
                return View("EditUser", inputModel);
            }
			
		}

        public ActionResult Add()
        {
            UserModel model = new UserModel();
            SetupRegisterViewModel(model);

		
            return View("AddUser", model);
        }

        [HttpPost]
				 public ActionResult AddUser(UserModel inputModel)
		        {
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.AddUser(UserMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListUserModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Add, output.Status));
          // เพิ่ม message แสดงในหน้าแม่
                TempData["UserMessage"] = listDisplay.Message;
                TempData["UserStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["UserId"] = output.Data.Id;
                }
		                return View("ListUser", listDisplay);
		            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
           
        }

        [HttpPost]
        public string DeleteUsers(string[] UserCheckbox)
        {
            ListUserModel input = new ListUserModel();
            if (ModelState.IsValid)
            {
                input = Delete(UserCheckbox, input);
            }

            if(input.IsSuccessed.GetValueOrDefault(false))
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
        }

        [HttpPost]
        public String DeleteUserById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            ServiceClient service = new ServiceClient();
            var output = service.DeleteUser(delList);

			//แสดง message ให้ class แม่
            TempData["UserMessage"] = Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status);
            TempData["UserStatus"] = output.Status;

            if (output.Status)
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
           
        }

        // Check does Username exist
        [HttpPost]
        public JsonResult doesUsernameExist(string Username, string Mode, string OldValue)
        {
			bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Trim().Equals(Username.Trim(), StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
				var service = new ServiceClient();
                var exist = service.ExistUser(Username).Data;
                return Json(!exist);
            }
            else
                return Json(true);
        }

		#region private methods

        private ListUserModel Delete(string[] inputList, ListUserModel input)
        {
            List<string> delList = new List<string>();
			var listDisplay = new ListUserModel();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                ServiceClient service = new ServiceClient();
                var output = service.DeleteUser(delList);
                listDisplay = PrepareRetrunFromOperation(input, output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status));

				TempData["UserMessage"] = listDisplay.Message;
                TempData["UserStatus"] = output.Status;
            }

            listDisplay.ListItems = PrepareSearch(listDisplay);
            return listDisplay;
        }

        private List<UserModel> PrepareSearch(ListUserModel input)
        {

            GetAllUserRequestModel searchInputs = new GetAllUserRequestModel()
            {
									Username = (input.UsernameSearch == null) ? ""  : input.UsernameSearch,
						
							Sort = "Username",
				SortType = sType.ASC
			};
            var result = Search(searchInputs);
            return result.List;
        }

        private GetAllResponseModel<UserModel> Search(GetAllUserRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            GetAllUserRequestDto gAllreq = new GetAllUserRequestDto { 
		  							Username = input.Username,
		                   SortType = input.SortType.ToString(),
                 Sort = input.Sort
            };
            var response = service.GetAllUser(gAllreq);
            var result = new GetAllResponseModel<UserModel>();
            result.List = new List<UserModel>();
            if(response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (UserDto responseDTO in response.Data)
                    {
                        UserModel resultModel = null;
                        UserDto tempDto = responseDTO;
                        resultModel = UserMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result;
        }

		private ListUserModel PrepareRetrunFromOperation(ListUserModel listModel, UserDto dto, bool status, string message)
		{
			if (status)
			{
				if (dto != null)
				{
					listModel.ListItems.Add(UserMapper.DtoToModel(dto));
				}
			}
			listModel.Message = message;
			listModel.IsSuccessed = status;
			return listModel;

		}



		
		private void SetupRegisterViewModel(UserModel model)
        {
            //เช็คว่ามี Attribute ที่เป็น DateTime ใน model หรือเปล่าถ้ามี + ปีไป 543 ถ้าปีเป็น ค.ศ.
            Utilities.Utilities.PrepareDateTimeProperity(model);
        }

		#endregion
    }
}
